package cn.sheep.zkapi;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.io.IOException;

/**
 * zk监听的使用
 * author: sheep.Old
 * qq: 64341393
 * Created 2018/5/31
 */
public class ZKWatchApi {

    static final String ZKSERVER = "demo01:2181,demo02:2181,demo03:2181";
    static final int TIMEOUT = 2000;


    ZooKeeper zk = null;

    /**
     * 监听节点数据变化
     */
    @Test
    public void testWatchDataChange() throws IOException, KeeperException, InterruptedException {
        zk = new ZooKeeper(ZKSERVER, TIMEOUT, new Watcher() {
            // 当接受到一个事件的时候，调用该方法
            public void process(WatchedEvent watchedEvent) {
                System.out.println("watchedEvent = " + watchedEvent);
                // true 循环注册监听
                try {
                    zk.getData(watchedEvent.getPath(), true, null);

                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        zk.getData("/grils", true, null);

        Thread.sleep(Long.MAX_VALUE);
        zk.close();
    }



    /**
     * 监听节点变化
	 *只能监听父节点下的第一级子节点，第二级子节点监听不到。
     */
    @Test
    public void testWatchNodeChildren() throws IOException, KeeperException, InterruptedException {

        zk = new ZooKeeper(ZKSERVER, TIMEOUT, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println("watchedEvent = " + watchedEvent);

                try {
                    zk.getChildren(watchedEvent.getPath(), true);

                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


        zk.getChildren("/grils", true);

        Thread.sleep(Long.MAX_VALUE);
        zk.close();


    }


}
